import {FormControl, FormGroup, NonNullableFormBuilder, Validators} from '@angular/forms';
import {Component, OnInit} from '@angular/core';
import {EmployeeService} from '../employee.service';
import {Router} from "@angular/router";
import {format} from "date-fns";
import {NzMessageService} from "ng-zorro-antd/message";

//定义手机号码正则表达式
const PHONE_NUMBER_REGEXP =
  /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/;

@Component({
  selector: 'app-employee-add',
  templateUrl: './employee-add.component.html',
  styleUrl: './employee-add.component.scss',
})

/**
 * 员工添加组件类
 */
export class EmployeeAddComponent implements OnInit {

  constructor(
    private employeesService: EmployeeService, //员工服务
    private nzMessageService: NzMessageService, //消息服务
    private fb: NonNullableFormBuilder, //表单构建器
    private router: Router //路由服务
  ) {
    //初始化表单
    this.addForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      gender: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phoneNumber: ['', [Validators.pattern(PHONE_NUMBER_REGEXP)]],
      joinDate: ['', [this.joinDateValidate]],
    });
  }

  addForm: FormGroup; //表单验证对象

  ngOnInit() {
  }

  //入职时间校验
  joinDateValidate(control: FormControl) {
    const selectDate = +control.value; //选择的日期转换为数字
    const curDate = +new Date(); //当前日期转换为数字
    if (selectDate > curDate) {
      return {date: true}; //如果选择的日期晚于当前日期，返回日期错误信息
    }
    return null; //选择的日期合法，返回null
  }

  //提交表单
  submitForm(): void {
    if (!this.addForm.valid) return; //如果表单无效则不执行添加逻辑
    let joinDate = this.addForm.value.joinDate; //获取入职日期
    //如果未选择入职日期，则默认设置为当前日期
    joinDate = joinDate ? joinDate : new Date();

    //将日期转换为"yyyy-MM-dd"格式
    joinDate = format(joinDate, 'yyyy-MM-dd');

    //将当前表单值和指定的加入日期合并成一个新的对象
    let params = Object.assign(
      {...this.addForm.value}, //将当前表单的值复制到新对象中
      {joinDate: joinDate} //将格式化后的日期加入到提交的参数中
    );
    //调用员工服务添加员工
    this.employeesService.add(params).subscribe(() => {
      this.router.navigate(['/']); //跳转页面
      this.nzMessageService.success('添加成功');
    });
  }

  //重置表单
  resetForm(e: MouseEvent): void {
    e.preventDefault(); //阻止事件的默认行为
    this.addForm.reset(); //重置表单
  }
}
